package cn.t.web.android;

import cn.t.annotation.Runtime;
import cn.t.constants.ParamConstants;
import cn.t.constants.ResponseError;
import cn.t.core.exception.BizException;
import cn.t.core.mode.PageInfoDTO;
import cn.t.core.mode.PageQueryDTO;
import cn.t.core.mode.Result;
import cn.t.dto.device.CabinetHandlingOCDTO;
import cn.t.dto.device.PickUpCompleteDTO;
import cn.t.dto.device.RoleSkuReq;
import cn.t.dto.device.UserRoleSkuDTO;
import cn.t.dto.device.group.CloseGroup;
import cn.t.dto.device.group.OpenGroup;
import cn.t.dto.device.vo.OpenCloseDTO;
import cn.t.dto.order.android.PickupDetailDTO;
import cn.t.enums.OptionTypeEnum;
import cn.t.facade.android.AndroidSessionFacade;
import cn.t.facade.android.engine.CabinetHandlingStrategy;
import cn.t.facade.device.DeviceFacade;
import cn.t.facade.order.WorkOrderFacade;
import cn.t.facade.user.RoleSkuFacade;
import cn.t.facade.user.UserSessionFacade;
import cn.t.vo.andriod.AndroidDeviceVO;
import cn.t.vo.user.UserSessionVO;
import cn.t.web.android.config.DeviceTypeHandlerFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 设备端-订单管理
 *
 * @author l
 */
@Slf4j
@RestController
@RequestMapping("runtime/order")
@AllArgsConstructor
@Runtime
public class AndroidCabinetOrderController {
    private final DeviceTypeHandlerFactory deviceTypeHandlerFactory;
    private final DeviceFacade deviceFacade;
    private final AndroidSessionFacade androidSessionFacade;
    private final RoleSkuFacade roleSkuFacade;

    private final UserSessionFacade userSessionFacade;
    private final WorkOrderFacade workOrderFacade;

    /**
     * 补货开门
     */
    @PostMapping("/replenishmentOpen")
    public Result<String> open(@Validated(OpenGroup.class) @RequestBody CabinetHandlingOCDTO model) {
        AndroidDeviceVO device = deviceFacade.getDeviceByImei(model.getImei());
        CabinetHandlingStrategy handler1 = deviceTypeHandlerFactory.getHandler(ParamConstants.CABINET_TYPE + device.getDeviceType());
        try {
            String requestId = handler1.replenishmentGoodsOpen(model);
            if (model.getOrderSn() != null && requestId != null) {
                return Result.success(requestId);
            }
        } catch (Exception e) {
            log.warn("补货开门异常", e);
            if (e.getMessage() != null) {
                throw new BizException(ResponseError.DATA_ERR, e.getMessage());
            } else {
                throw new BizException(ResponseError.DATA_ERR, "开门异常,请联系管理员!");
            }
        }
        throw new BizException(ResponseError.DATA_ERR, "补货开门异常," + model.getOrderSn());
    }

    /**
     * 补货关门
     */
    @PostMapping("/replenishmentClose")
    public Result<Boolean> close(@Validated(CloseGroup.class) @RequestBody CabinetHandlingOCDTO model) {
        long startTime = System.currentTimeMillis();
        AndroidDeviceVO device = deviceFacade.getDeviceByImei(model.getImei());
        CabinetHandlingStrategy handler1 = deviceTypeHandlerFactory.getHandler(ParamConstants.CABINET_TYPE + device.getDeviceType());
        Result<Boolean> result = Result.success(true);
        try {
            model.setDeviceId(device.getDeviceId());
            Boolean aBoolean = handler1.replenishmentGoodsClose(model);

            if (!aBoolean) {
                log.warn("补货关门失败 {}", model.getOrderSn());
                result = Result.fail(ResponseError.DATA_ERR.getCode(), "补货关门失败");
            }
        } catch (Exception e) {
            log.warn("补货关门异常", e);
            if (e.getMessage() != null) {
                throw new BizException(ResponseError.DATA_ERR, e.getMessage());
            } else {
                throw new BizException(ResponseError.DATA_ERR, "关门异常,请联系管理员!");
            }
        }
        log.info("补货关门-结束耗时 {}", System.currentTimeMillis() - startTime);
        return result;
    }

    /**
     * 领料开门
     */
    @PostMapping("/orderOpen")
    public Result<String> orderOpen(@Validated(OpenGroup.class) @RequestBody CabinetHandlingOCDTO model) {
        AndroidDeviceVO device = deviceFacade.getDeviceByImei(model.getImei());
        CabinetHandlingStrategy handler1 = deviceTypeHandlerFactory.getHandler(ParamConstants.CABINET_TYPE + device.getDeviceType());
        try {
            OpenCloseDTO openDoor = handler1.openDoor(model, OptionTypeEnum.order_open);
            return Result.success(openDoor.getOrderSn());
        } catch (Exception e) {
            log.warn("领料开门异常", e);
            if (e.getMessage() != null) {
                throw new BizException(ResponseError.DATA_ERR, e.getMessage());
            } else {
                throw new BizException(ResponseError.DATA_ERR, "开门异常,请联系管理员!");
            }
        }


    }

    /**
     * 领料关门
     */
    @PostMapping("/orderClose")
    public PickupDetailDTO orderClose(@Validated(CloseGroup.class) @RequestBody CabinetHandlingOCDTO model) {
        long startTime = System.currentTimeMillis();

        AndroidDeviceVO device = deviceFacade.getDeviceByImei(model.getImei());
        CabinetHandlingStrategy handler1 = deviceTypeHandlerFactory.getHandler(ParamConstants.CABINET_TYPE + device.getDeviceType());
        UserSessionVO session = userSessionFacade.getSession();
        try {

            PickupDetailDTO pickupDetailDTO = handler1.orderClose(model, OptionTypeEnum.order_open, session);
            if (pickupDetailDTO == null) {
                log.warn("领料关门失败 pickupDetailDTO isnull  {}", model.getOrderSn());
                return new PickupDetailDTO();
            }
            log.info("领料关门 -结束耗时 {}", System.currentTimeMillis() - startTime);
            return pickupDetailDTO;

        } catch (Exception e) {
            log.warn("领料关门异常", e);
            if (e.getMessage() != null) {
                throw new BizException(ResponseError.DATA_ERR, e.getMessage());
            } else {
                throw new BizException(ResponseError.DATA_ERR, "关门异常,请联系管理员!");
            }
        } finally {
            if (session != null) {
                androidSessionFacade.deleteDayOverPickNumSession(session.getUserId(), device.getFirmId());
            }
        }

    }

    /**
     * 领料员领料权限查询
     */
    @PostMapping("/pickupPermission")

    public PageInfoDTO<UserRoleSkuDTO> pickupPermission(@RequestBody PageQueryDTO<RoleSkuReq> req) {
        AndroidDeviceVO device = deviceFacade.getDeviceByImei(req.getParam().getImei());
        if (req.getParam() != null) {
            if (req.getParam().getWorkOrderSn() == null) {
                return roleSkuFacade.querySkuRoleByUser(req, device);
            } else {
                return workOrderFacade.querySkuRoleByUser(req, device);
            }
        }

        throw new BizException(ResponseError.DATA_ERR, "参数错误");

    }

    /**
     * 开始领用
     */
    @PostMapping("/pickupStart")
    public Result<String> pickupStart(@RequestBody CabinetHandlingOCDTO req) {

        long startTime = System.currentTimeMillis();

        AndroidDeviceVO device = deviceFacade.getDeviceByImei(req.getImei());
        CabinetHandlingStrategy handler1 = deviceTypeHandlerFactory.getHandler(ParamConstants.CABINET_TYPE + device.getDeviceType());
        UserSessionVO session = userSessionFacade.getSession();
        try {

            String orderSn = handler1.startPick(req);
            if (orderSn == null) {
                log.warn("领用下单失败 pickupDetailDTO isnull  {}", req.getOrderSn());
               throw new BizException(ResponseError.DATA_ERR, "领料失败");
            }
            log.info("领用下单耗时pickupStart {}", System.currentTimeMillis() - startTime);
            return Result.success(orderSn);

        } catch (Exception e) {
            log.warn("领用下单失败", e);
            if (e.getMessage() != null) {
                throw new BizException(ResponseError.DATA_ERR, e.getMessage());
            } else {
                throw new BizException(ResponseError.DATA_ERR, "领用下单失败,请联系管理员!");
            }
        } finally {
            if (session != null) {
                androidSessionFacade.deleteDayOverPickNumSession(session.getUserId(), device.getFirmId());
            }
        }
    }




    /**
     * 领用完毕
     */
    @PostMapping("/pickUpComplete")
    public PickupDetailDTO pickUpComplete(@RequestBody PickUpCompleteDTO model) {
        AndroidDeviceVO device = deviceFacade.getDeviceByImei(model.getImei());
        CabinetHandlingStrategy handler1 = deviceTypeHandlerFactory.getHandler(ParamConstants.CABINET_TYPE + device.getDeviceType());
        PickupDetailDTO pickupDetailDTO = new PickupDetailDTO();
        try {
            pickupDetailDTO.setPickupDetail(handler1.pickUpComplete(model,device));

        } catch (Exception e) {
            log.warn("领用完成异常", e);
            if (e.getMessage() != null) {
                throw new BizException(ResponseError.DATA_ERR, e.getMessage());
            } else {
                throw new BizException(ResponseError.DATA_ERR, "领用失败,请联系管理员!");
            }
        }
        return pickupDetailDTO;
    }


}